<template>
  <div class="rich-text-input">
    <div
      :id="idName"
      ref="inputBoxRef"
      class="richtext"
      :class="{ 'input-box': props.Boolean }"
      contenteditable="true"
      :placeholder="props.hitContent"
      spellcheck="false"
      :style="{ width, minHeight: height }"
    ></div>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
const props = defineProps({
  Boolean: {
    type: Boolean,
    default: true
  },
  idName: {
    type: String,
    default: ''
  },
  /* v-modelb绑定的值 */
  modelValue: {
    type: String,
    default: ''
  },
  hitContent: {
    type: String,
    default: '输入评论 (Enter换行,Ctrl+Enter发送)'
  },

  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '69px'
  }
})

const inputBoxRef = ref(null)

const emits = defineEmits(['updata:modelValue'])
watch(
  () => {
    props.Boolean
  },
  (val) => {
    console.log(val, 'val')
    props.Boolean = val
  }
)
onMounted(() => {
  watch(
    () => props.modelValue,
    (newValue, oldValue) => {
      if (newValue !== inputBoxRef.value.innerHTML) {
        inputBoxRef.value.innerHTML = newValue
      }
    }
  )
  // let inputBox = document.querySelector('.input-box')
  console.log(inputBoxRef.value)
  if (inputBoxRef.value) {
    inputBoxRef.value.addEventListener('blur', (event) => {
      // console.log(inputBox.innerHTML)
      /* 将html内容emit到父组件 */
      emits('updata:modelValue', inputBoxRef.value.innerHTML)
    })
  }
})

defineExpose({
  inputBoxRef
})
</script>

<style lang="scss" scoped>
.richtext {
  position: relative;
  padding: 8px 12px;
  color: #252933;
  outline: none;
  min-height: 64px;
  box-sizing: border-box;
  line-height: 22px;
  font-size: 14px;
  resize: both;
  background-color: #f2f3f5;
  border-radius: 4px;
  transition: all 0.3s;
  :deep(img) {
    vertical-align: middle;
    margin: 0 3px;
  }
}
.richtext:focus {
  border-color: #00a0e9;
  box-shadow: 0 0 0 1px #00a0e9;
  background-color: #fff;
}
.richtext:empty::before {
  content: attr(placeholder);
  color: #ccc;
  font-size: 14px;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  padding: 8px 13px;
  letter-spacing: 2px;
}
</style>
